<template>
  <div class="space-y-8">
    <!-- Overview Stats -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
      <Card class="bg-gradient-to-br from-blue-50 to-blue-100 dark:from-blue-950 dark:to-blue-900">
        <CardContent class="pt-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-blue-600 dark:text-blue-400">{{ t('dashboard.totalTests') }}</p>
              <p class="text-3xl font-bold text-blue-700 dark:text-blue-300">{{ testResults.length }}</p>
            </div>
            <BarChart3 class="w-8 h-8 text-blue-500"/>
          </div>
        </CardContent>
      </Card>

      <Card class="bg-gradient-to-br from-green-50 to-green-100 dark:from-green-950 dark:to-green-900">
        <CardContent class="pt-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-green-600 dark:text-green-400">{{ t('dashboard.averageScore') }}</p>
              <p class="text-3xl font-bold text-green-700 dark:text-green-300">{{ userProfile.averageScore }}</p>
            </div>
            <Target class="w-8 h-8 text-green-500"/>
          </div>
        </CardContent>
      </Card>

      <Card class="bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-950 dark:to-purple-900">
        <CardContent class="pt-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-purple-600 dark:text-purple-400">{{ t('dashboard.currentLevel') }}</p>
              <p class="text-3xl font-bold text-purple-700 dark:text-purple-300">{{ userProfile.level }}</p>
            </div>
            <Trophy class="w-8 h-8 text-purple-500"/>
          </div>
        </CardContent>
      </Card>

      <Card class="bg-gradient-to-br from-orange-50 to-orange-100 dark:from-orange-950 dark:to-orange-900">
        <CardContent class="pt-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-orange-600 dark:text-orange-400">{{ t('dashboard.unlockedAchievements') }}</p>
              <p class="text-3xl font-bold text-orange-700 dark:text-orange-300">{{ unlockedAchievements.length }}</p>
            </div>
            <Award class="w-8 h-8 text-orange-500"/>
          </div>
        </CardContent>
      </Card>

      <!-- AI对战统计卡片 -->
      <Card v-if="aiBattleResults.length > 0"
            class="bg-gradient-to-br from-purple-50 to-purple-100 dark:from-purple-950 dark:to-purple-900">
        <CardContent class="pt-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-purple-600 dark:text-purple-400">{{ t('dashboard.aiWinRate') }}</p>
              <p class="text-3xl font-bold text-purple-700 dark:text-purple-300">{{ aiBattleWinRate }}%</p>
            </div>
            <Sword class="w-8 h-8 text-purple-500"/>
          </div>
          <div class="mt-2 text-xs text-purple-600 dark:text-purple-400">
            {{ aiBattleWins }}/{{ aiBattleResults.length }} {{ t('dashboard.wins') }}
          </div>
        </CardContent>
      </Card>

      <!-- 测试覆盖率统计 -->
      <Card class="bg-gradient-to-br from-cyan-50 to-cyan-100 dark:from-cyan-950 dark:to-cyan-900">
        <CardContent class="pt-6">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-cyan-600 dark:text-cyan-400">{{ t('dashboard.testCoverage') }}</p>
              <p class="text-3xl font-bold text-cyan-700 dark:text-cyan-300">{{ testCoverage }}%</p>
            </div>
            <Target class="w-8 h-8 text-cyan-500"/>
          </div>
          <div class="mt-2 text-xs text-cyan-600 dark:text-cyan-400">
            {{ completedTestsCount }}/{{ tests.length }} {{ t('dashboard.testsCompleted') }}
          </div>
        </CardContent>
      </Card>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <!-- Left Column -->
      <div class="lg:col-span-2 space-y-6">
        <!-- Category Performance -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <Brain class="w-5 h-5"/>
              {{ t('dashboard.categoryPerformance') }}
            </CardTitle>
          </CardHeader>
          <CardContent class="space-y-6">
            <div v-for="category in categoryPerformance" :key="category.category" class="space-y-2">
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                  <div :class="['w-3 h-3 rounded-full bg-current', category.color]"/>
                  <span class="font-medium">{{ category.name }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <span class="text-sm text-muted-foreground">
                    {{ category.completed }}/{{ category.total }} {{ t('dashboard.completed') }}
                  </span>
                  <Badge class="min-w-[60px] justify-center" variant="outline">
                    {{ category.score }}{{ t('dashboard.score') }}
                  </Badge>
                </div>
              </div>
              <Progress :model-value="(category.completed / category.total) * 100" class="h-3"/>
              <div class="flex justify-between text-xs text-muted-foreground">
                <span>{{ t('dashboard.completion') }}: {{ Math.round((category.completed / category.total) * 100) }}%</span>
                <span>{{ t('dashboard.avgScore') }}: {{ category.score }}</span>
              </div>
            </div>
          </CardContent>
        </Card>

        <!-- Progress Over Time -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <TrendingUp class="w-5 h-5"/>
              {{ t('dashboard.progressTrend') }}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div v-if="progressData.every(week => week.count === 0)" class="text-center py-8 text-muted-foreground">
              <Activity class="w-12 h-12 mx-auto mb-4 opacity-50"/>
              <p>{{ t('dashboard.noData') }}</p>
              <p class="text-sm mt-2">{{ t('dashboard.completeMoreTests') }}</p>
            </div>
            <div v-else class="space-y-4">
              <div v-for="week in progressData" :key="week.week"
                   class="flex items-center justify-between p-3 bg-[rgba(234,244,255,0.6)] rounded-lg">
                <div class="flex items-center gap-3">
                  <Calendar class="w-4 h-4 text-muted-foreground"/>
                  <span class="font-medium">{{ t('dashboard.week', { week: week.week }) }}</span>
                </div>
                <div class="flex items-center gap-4">
                  <span class="text-sm text-muted-foreground">{{ t('dashboard.testsCount', { count: week.count }) }}</span>
                  <Badge :variant="week.score >= 80 ? 'default' : week.score >= 60 ? 'secondary' : 'outline'">
                    {{ week.score || t('dashboard.noDataAvailable') }}
                  </Badge>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <!-- Recent Tests -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <Activity class="w-5 h-5"/>
              {{ t('dashboard.recentTests') }}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div v-if="recentTests.length > 0" class="space-y-3">
              <div v-for="(result, index) in recentTests.slice(0, 5)" :key="index"
                   class="flex items-center justify-between p-3 border rounded-lg">
                <div>
                  <h4 class="font-medium flex items-center gap-2">
                    {{ result.testType }}
                    <Badge v-if="result.details?.battleMode"
                           class="text-xs bg-purple-50 text-purple-600 border-purple-200"
                           variant="outline">
                      <Bot class="w-3 h-3 mr-1"/>
                      {{ t('dashboard.aiBattle') }}
                    </Badge>
                  </h4>
                  <p class="text-sm text-muted-foreground">
                    {{ formatRecentDate(result.completedAt || result.date || result.timestamp) }}
                  </p>
                </div>
                <div class="text-right">
                  <div class="text-xl font-bold text-primary">{{ result.score }}</div>
                  <div v-if="result.percentile" class="text-xs text-muted-foreground">
                    {{ t('dashboard.percentile', { percentile: Math.round(result.percentile) }) }}
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-8 text-muted-foreground">
              <BarChart3 class="w-12 h-12 mx-auto mb-4 opacity-50"/>
              <p>{{ t('dashboard.noTestHistory') }}</p>
              <Button
                class="mt-4 bg-gradient-to-r from-slate-600 to-gray-700 hover:from-slate-700 hover:to-gray-800 text-white shadow-sm hover:shadow-md transition-all duration-200"
                @click="onStartTest('reaction')"
              >
                {{ t('dashboard.startFirstTest') }}
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      <!-- Right Column -->
      <div class="space-y-6">
        <!-- Strengths & Weaknesses -->
        <Card v-if="strengthsAndWeaknesses.strengths.length > 0">
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <Zap class="w-5 h-5"/>
              {{ t('dashboard.abilityAnalysis') }}
            </CardTitle>
          </CardHeader>
          <CardContent class="space-y-4">
            <div>
              <h4 class="font-medium text-green-600 mb-2">{{ t('dashboard.strengths') }}</h4>
              <div class="space-y-2">
                <div v-for="(strength, index) in strengthsAndWeaknesses.strengths" :key="index"
                     class="flex items-center justify-between p-2 bg-green-50 dark:bg-green-950 rounded">
                  <span class="text-sm">{{ strength.testType }}</span>
                  <Badge class="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-100" variant="secondary">
                    {{ Math.round(strength.avgScore) }}
                  </Badge>
                </div>
              </div>
            </div>

            <div>
              <h4 class="font-medium text-orange-600 mb-2">{{ t('dashboard.weaknesses') }}</h4>
              <div class="space-y-2">
                <div v-for="(weakness, index) in strengthsAndWeaknesses.weaknesses" :key="index"
                     class="flex items-center justify-between p-2 bg-orange-50 dark:bg-orange-950 rounded">
                  <span class="text-sm">{{ weakness.testType }}</span>
                  <Badge class="border-orange-200 text-orange-800 dark:border-orange-800 dark:text-orange-200"
                         variant="outline">
                    {{ Math.round(weakness.avgScore) }}
                  </Badge>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <!-- Recent Achievements -->
        <Card>
          <CardHeader>
            <CardTitle class="flex items-center gap-2">
              <Trophy class="w-5 h-5"/>
              {{ t('dashboard.recentAchievements') }}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div v-if="unlockedAchievements.length > 0" class="space-y-3">
              <div
                v-for="achievement in unlockedAchievements.sort((a, b) => (b.unlockedDate?.getTime() || 0) - (a.unlockedDate?.getTime() || 0)).slice(0, 3)"
                :key="achievement.id" class="flex items-center gap-3 p-3 bg-yellow-50 dark:bg-yellow-950 rounded-lg">
                <component :is="achievement.icon" class="w-6 h-6 text-yellow-500"/>
                <div class="flex-1">
                  <h4 class="font-medium">{{ achievement.name }}</h4>
                  <p class="text-sm text-muted-foreground">{{ achievement.description }}</p>
                  <p v-if="achievement.unlockedDate" class="text-xs text-muted-foreground mt-1">
                    {{ formatUnlockedDate(achievement.unlockedDate) }}
                  </p>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-6 text-muted-foreground">
              <Trophy class="w-8 h-8 mx-auto mb-2 opacity-50"/>
              <p class="text-sm">{{ t('dashboard.unlockAchievementsPrompt') }}</p>
            </div>
          </CardContent>
        </Card>

        <!-- Quick Actions -->
        <Card>
          <CardHeader>
            <CardTitle>{{ t('dashboard.quickStart') }}</CardTitle>
          </CardHeader>
          <CardContent class="space-y-3">
            <Button
              class="w-full bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
              @click="onStartTest('reaction')"
            >
              <Zap class="w-4 h-4 mr-2"/>
              {{ t('dashboard.reactionTimeTest') }}
            </Button>
            <Button
              class="w-full bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
              @click="onStartTest('memory')"
            >
              <Brain class="w-4 h-4 mr-2"/>
              {{ t('dashboard.memoryTest') }}
            </Button>
            <Button
              class="w-full bg-gradient-to-r from-orange-500 to-orange-600 hover:from-orange-600 hover:to-orange-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
              @click="onStartTest('logical')"
            >
              <Puzzle class="w-4 h-4 mr-2"/>
              {{ t('dashboard.logicalReasoningTest') }}
            </Button>
            <Button
              class="w-full bg-gradient-to-r from-emerald-500 to-emerald-600 hover:from-emerald-600 hover:to-emerald-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
              @click="onStartTest('creative-thinking')"
            >
              <Sparkles class="w-4 h-4 mr-2"/>
              {{ t('dashboard.creativeThinkingTest') }}
            </Button>
            <Button
              class="w-full bg-gradient-to-r from-rose-500 to-rose-600 hover:from-rose-600 hover:to-rose-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
              @click="onStartTest('emotion-recognition')"
            >
              <Smile class="w-4 h-4 mr-2"/>
              {{ t('dashboard.emotionRecognitionTest') }}
            </Button>
            <Button
              class="w-full bg-gradient-to-r from-indigo-500 to-indigo-600 hover:from-indigo-600 hover:to-indigo-700 text-white shadow-sm hover:shadow-md transition-all duration-200"
              @click="onStartTest('ai-battle')"
            >
              <Bot class="w-4 h-4 mr-2"/>
              {{ t('dashboard.aiBattleMode') }}
            </Button>
          </CardContent>
        </Card>
      </div>
    </div>
  </div>
</template>

<script setup>
import {computed} from 'vue';
import {
  BarChart3,
  TrendingUp,
  Trophy,
  Target,
  Brain,
  Zap,
  Award,
  Calendar,
  Activity,
  Sword,
  Bot,
  Puzzle,
  Sparkles,
  Smile
} from 'lucide-vue-next';
import { useI18n } from "vue-i18n";
import { getTests, getTestCategories } from '../constants/tests';

const { t } = useI18n();

const tests = computed(() => getTests(t));
const testCategories = computed(() => getTestCategories(t));

const props = defineProps(['testResults', 'userProfile', 'achievements']);
const emit = defineEmits(['startTest']);

const onStartTest = (testType) => {
  emit('startTest', testType);
};

const categoryPerformance = computed(() => {
  return Object.entries(testCategories.value).map(([categoryKey, categoryInfo]) => {
    const categoryResults = props.testResults.filter(result => {
      const test = tests.value.find(t =>
        t.id === result.testType ||
        t.title === result.testType ||
        result.testType.includes(t.title.replace('测试', ''))
      );
      return test && test.category === categoryKey;
    });

    const avgScore = categoryResults.length > 0
      ? categoryResults.reduce((sum, result) => sum + result.score, 0) / categoryResults.length
      : 0;

    return {
      category: categoryKey,
      name: categoryInfo.name,
      score: Math.round(avgScore),
      completed: categoryResults.length,
      total: categoryInfo.tests.length,
      color: categoryInfo.color
    };
  });
});

const recentTests = computed(() => {
  return props.testResults
    .filter(result => {
      const testDate = new Date(result.completedAt || result.date || result.timestamp || new Date());
      return testDate instanceof Date && !isNaN(testDate.getTime());
    })
    .sort((a, b) => {
      const dateA = new Date(a.completedAt || a.date || a.timestamp || new Date());
      const dateB = new Date(b.completedAt || b.date || b.timestamp || new Date());
      return dateB.getTime() - dateA.getTime();
    })
    .slice(0, 10);
});

const strengthsAndWeaknesses = computed(() => {
  if (props.testResults.length < 3) return {strengths: [], weaknesses: []};

  const testScores = props.testResults.reduce((acc, result) => {
    if (!acc[result.testType]) {
      acc[result.testType] = [];
    }
    acc[result.testType].push(result.score);
    return acc;
  }, {});

  const avgScores = Object.entries(testScores).map(([testType, scores]) => ({
    testType,
    avgScore: scores.reduce((sum, score) => sum + score, 0) / scores.length
  }));

  avgScores.sort((a, b) => b.avgScore - a.avgScore);

  const strengths = avgScores.slice(0, 2);
  const weaknesses = avgScores.slice(-2).reverse();

  return {strengths, weaknesses};
});

const progressData = computed(() => {
  const last30Days = props.testResults.filter(result => {
    const testDate = new Date(result.completedAt || result.date || result.timestamp || new Date());
    if (!testDate || isNaN(testDate.getTime())) return false;
    const daysDiff = (Date.now() - testDate.getTime()) / (1000 * 60 * 60 * 24);
    return daysDiff <= 30;
  });

  const weeklyData = [];
  for (let i = 0; i < 4; i++) {
    const weekStart = new Date();
    weekStart.setDate(weekStart.getDate() - (i + 1) * 7);
    const weekEnd = new Date();
    weekEnd.setDate(weekEnd.getDate() - i * 7);

    const weekTests = last30Days.filter(result => {
      const testDate = new Date(result.completedAt || result.date || result.timestamp || new Date());
      return testDate >= weekStart && testDate < weekEnd;
    });

    const avgScore = weekTests.length > 0
      ? weekTests.reduce((sum, result) => sum + result.score, 0) / weekTests.length
      : 0;

    weeklyData.unshift({
      week: `${4 - i}`,
      score: Math.round(avgScore),
      count: weekTests.length
    });
  }

  return weeklyData;
});

const unlockedAchievements = computed(() => props.achievements.filter(a => a.unlocked));

const aiBattleResults = computed(() => props.testResults.filter(r => r.details?.battleMode));
const aiBattleWins = computed(() => aiBattleResults.value.filter(r => r.details?.winner === 'player').length);
const aiBattleWinRate = computed(() => aiBattleResults.value.length > 0 ? Math.round((aiBattleWins.value / aiBattleResults.value.length) * 100) : 0);

const formatRecentDate = (dateStr) => {
  const testDate = new Date(dateStr || new Date());
  if (testDate && !isNaN(testDate.getTime())) {
    return testDate.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  }
  return t('dashboard.justCompleted');
};

const formatUnlockedDate = (date) => {
  if (date && !isNaN(new Date(date).getTime())) {
    return new Date(date).toLocaleDateString('zh-CN');
  }
  return t('dashboard.recentlyUnlocked');
};

const testCoverage = computed(() => {
  return Math.round((new Set(props.testResults.map(r => r.testType)).size / tests.value.length) * 100)
})

const completedTestsCount = computed(() => {
  return new Set(props.testResults.map(r => r.testType)).size
})

</script>